package cn.edu.sdjzu.xg2121.service;

import cn.edu.sdjzu.xg2121.dao.DepartmentDao;
import cn.edu.sdjzu.xg2121.dao.SchoolDao;
import cn.edu.sdjzu.xg2121.domain.Department;
import cn.edu.sdjzu.xg2121.domain.Teacher;
import cn.edu.sdjzu.xg2121.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DepartmentService {
    private static DepartmentService departmentService =  new DepartmentService();
    private DepartmentService(){}
    public static DepartmentService getInstance(){
        return departmentService;
    }
    public static DepartmentDao departmentDao = new DepartmentDao();
    public boolean delete(int id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Teacher teacher = TeacherService.getInstance().find(id);
        if (teacher != null) {
            System.out.println("仍有下属系");
        } else {
            return DepartmentDao.getInstance().delete(id, connection);
        }
        return true;
    }
    public boolean update(Department department) throws SQLException {
        return departmentDao.update(department);
    }
    public Department find(int id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Department department = DepartmentDao.getInstance().find(id);
        return department;
    }
    public void add(Department department) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
            DepartmentDao.getInstance().add(department);
            SchoolDao.getInstance().add(department.getSchool());
            System.out.println("添加成功");
            connection.commit();
        }finally {
            connection.setAutoCommit(true);
        }
    }
}
